import * as React from 'react';
import {
  insertParagraph, createContentControl, replaceContentInControl,
  addAndBindControl, getResourceGuid, showSelection,
  getSelectedDataAsync, insertTextAfterParagraph, writeMyOOXMLContent,
  insertImage, showXMLPartsInNamespace, addXMLPart
} from '../../utils/WordUtil'
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { TextField } from 'office-ui-fabric-react/lib/TextField';

import './styles.less';
import { DialogBlockingExample } from './DialogBlockingExample';
import { BodyExample } from './BodyExample';
import ControlExample from './ControlExample';
import { getImageAsBase64 } from '../../utils/base64Files';

export default class App extends React.Component<any, any> {

  constructor(props, context) {
    super(props, context);
    this.state = {
      message: 0,
      code: '',
      originText: ''
    };

  }

  componentDidMount() {
    this.setState({
      message: 1
    })

    // 获取id
    showXMLPartsInNamespace()

    // Office.context.document.addHandlerAsync(
    //   Office.EventType.DocumentSelectionChanged, this.selectChange, function (result) { }
    // );

    function getResourceGuid1() {
      console.log('绑定事件 getSelectedResourceAsync')
      Office.context.document.getSelectedResourceAsync(
        function (result) {
          console.log(result)
          // if (result.status === Office.AsyncResultStatus.Failed) {
          //   onError(result.error);
          // }
          // else {
          //   $('#message').html('Resource GUID: ' + result.value);
          // }
        }
      );
    }
    // Office.context.document.addHandlerAsync(
    //   Office.EventType.ResourceSelectionChanged, getResourceGuid1, function (result) { }
    // );
  }
  componentWillUnmount() {
    // Office.context.document.removeHandlerAsync(
    //   Office.EventType.DocumentSelectionChanged,
    //   { handler: this.selectChange },
    //   function (result) { }
    // );
  }

  clear = async () => {
    return Word.run(async context => {
      var body = context.document.body;
      body.clear();
    })
  }

  // 修改文字颜色
  changeFontColor = async () => {
    Word.run(async context => {
      // var body = context.document.body;
      // body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);
      const range = context.document.getSelection();
      range.load('text');
      // Update font color
      range.font.color = 'red';
      return context.sync()
    });
  }

  handleEventChange = () => {
    getResourceGuid()
  }

  public selectChange = ({ document, type }) => {
    console.log(`点击.`, type);

    const { message } = this.state
    this.setState({
      message: message + 1
    })
    // showSelection() // 获取html
    // getResourceGuid()
  }

  insertImage() {
    console.log(`插入图片.`);
    const imgData = getImageAsBase64()
    insertImage(imgData)
  }
  insertParagraph() {
    console.log(`查The insertParagraph.`);
    insertParagraph() // TODO 写法有问题
  }
  insertTextAfterParagraph1() {
    console.log(`查The insertTextAfterParagraph1.`);
    insertTextAfterParagraph()
  }
  createContentControl() {
    createContentControl()
  }
  replaceContentInControl() {
    replaceContentInControl()
  }
  getSelectedDataAsync() {
    getSelectedDataAsync()
  }
  writeMyOOXMLContent() {
    writeMyOOXMLContent()
  }
  addAndBindControl() {
    addAndBindControl()
  }

  insertHTML() {
    Word.run(function (context) {
      const blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", "After");
      blankParagraph.insertHtml('<p style="font-family: verdana;">Inserted HTML.</p><p>Another paragraph</p>', "End");

      return context.sync();
    }).catch(function (error) {
      console.log('Error:' + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  }

  insertTable() {
    Word.run(function (context) {
      const secondParagraph = context.document.body.paragraphs.getFirst().getNext();

      const tableData = [
        ["Name", "ID", "Birth City"],
        ["Bob", "434", "Chicago"],
        ["Sue", "719", "Havana"],
      ];
      secondParagraph.insertTable(3, 3, "After", tableData);

      return context.sync();
    }).catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
    });
  }

  onChangeCode = e => {
    this.setState({
      code: e.target.value
    })
  }

  getInfo = () => {
    // console.log('test:', Office.context.diagnostics)
    document.getElementById("message").innerText = JSON.stringify(Office.context.diagnostics)
  }

  evalCode = () => {
    eval(this.state.code)
  }

  clearCode = () => {
    this.setState({
      code: ''
    })
  }

  addOfoBind = () => {
    Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'ofoBind' }, asyncResult => {
      if (asyncResult.status == Office.AsyncResultStatus.Failed) {
        console.log('error')
      } else {
        asyncResult.value.getDataAsync(newValue => {
          this.setState({
            ofoName: newValue.value
          })
        })
        Office.select("bindings#ofoBind").addHandlerAsync(Office.EventType.BindingDataChanged, this.dataChanged);
      }
    })
  }

  addOfoBindEvent = () => {
    Office.select("bindings#ofoBind").addHandlerAsync(Office.EventType.BindingDataChanged, this.dataChanged);
  }


  removeOfoBindEvent = () => {
    Office.select("bindings#ofoBind").removeHandlerAsync(
      Office.EventType.BindingDataChanged, { handler: this.dataChanged });
  }

  dataChanged = asyncResult => {
    // console.log('newValue', JSON.stringify(asyncResult.binding))
    asyncResult.binding.getDataAsync(newValue => {
      this.setState({
        ofoName: newValue.value
      })
    })
  }

  modifyOfo = (e, newValue) => {
    this.setState({
      ofoName: newValue
    }, () => {
      Office.select("bindings#ofoBind", function onError() { }).setDataAsync(newValue);
    })
  }

  onChangeSetting = (e, newValue) => {
    this.setState({
      wordId: newValue
    }, () => {
      Office.context.document.settings.set('wordId', newValue);
    })
  }

  onSaveSetting = () => {
    Office.context.document.settings.saveAsync(function (asyncResult) {
      console.log(asyncResult)
    });
  }

  // 替换选中文字中的部分文字
  replaceWordContent = () => {
    Word.run(context => {
      // var textSample = '这是一段添加的内容';
      var range = context.document.getSelection();
      context.load(range, 'text')
      // range.delete()
      // range.insertText(textSample, Word.InsertLocation.end);
      return context.sync().then(() => {
        this.setState({
          originText: range.text
        })
      });
    })
  }
  render() {
    const { message, code } = this.state
    return (
      <div className='container'>
        <div id="content-header">
          <div className="padding">
            <h1>Welcome</h1>
            <div className="link-wrap"><a href="assets/chart.html">跳转到图表的页面</a></div>
            <div>
              <PrimaryButton className="pull-right" onClick={this.clear}>清空文档</PrimaryButton>
            </div>
            <br />
            <div>
              <PrimaryButton className="pull-right" onClick={this.getInfo}>获取当前宿主信息</PrimaryButton>
            </div>

            <div id="message">测试显示什么</div>
            <div style={{ margin: '15px 0' }}>{`显示内容为: ${message}`}</div>
            {/* <DialogBlockingExample /> */}
            <BodyExample />
            <ControlExample />
          </div>
        </div>
        <div id="content-main">
          <h2>执行代码</h2>
          <div className="padding">
            <TextField label="代码片段" multiline rows={4} value={code} onChange={this.onChangeCode} />
            <div className="padding">
              <DefaultButton className="ms-button" onClick={this.clearCode}>清空</DefaultButton>
              <PrimaryButton className="ms-button" onClick={this.evalCode}>执行</PrimaryButton>
            </div>
          </div>
          <h2>插入</h2>
          <div className="button-wrap">
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.replaceWordContent}>替换选中段落部分内容</PrimaryButton>
            </div>
            <div>{`显示selection内容：${this.state.originText}`}</div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="click" onClick={this.getSelectedDataAsync}>getSelectedDataAsync </PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.writeMyOOXMLContent}>writeMyOOXMLContent </PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.insertHTML}>insertHTML </PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.insertTable}>insertTable </PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="insert-paragraph" onClick={this.insertParagraph}>Insert Paragraph1</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="insert-paragraph" onClick={this.insertTextAfterParagraph1}>Insert TextAfter current Paragraph1</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.createContentControl}>createContentControl</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.replaceContentInControl}>replaceContentInControl</PrimaryButton>
            </div>

            <div className="padding">
              <PrimaryButton className="ms-Button" id="insert-image" onClick={this.insertImage}>Insert Image</PrimaryButton>
            </div>

            <div className="padding">
              {this.state.xmlId}
              <TextField label="xmlId" value={this.state.xmlId} onChange={(e, newValue) => this.setState({
                xmlId: newValue
              })} />
              <PrimaryButton className="ms-Button" id="insert-image" onClick={() => addXMLPart(this.state.xmlId)}>addXMLPart</PrimaryButton>
            </div>
          </div>
          <h2>自定义设置</h2>
          <div className="button-wrap">
            当前wordID: {Office.context.document.settings.get('wordId')}
            <TextField label="id" value={this.state.wordId} onChange={this.onChangeSetting} />
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-style" onClick={this.onSaveSetting}>保存</PrimaryButton>
            </div>
          </div>
          <h2>绑定例子</h2>
          <div className="button-wrap">
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-style" onClick={this.addOfoBind}>添加选中的绑定值</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-style" onClick={this.addOfoBindEvent}>添加绑定事件</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-style" onClick={this.removeOfoBindEvent}>移除绑定事件</PrimaryButton>
            </div>
            <div className="padding">
              <TextField label="ofo简称" value={this.state.ofoName} onChange={this.modifyOfo} />
              {/* <PrimaryButton className="ms-Button" id="apply-custom-style" onClick={this.modifyOfo}>修改绑定值</PrimaryButton> */}
            </div>
          </div>
          <h2>修改样式</h2>
          <div className="button-wrap">
            <div className="padding">
              <PrimaryButton className="ms-Button" onClick={this.changeFontColor}>change selected text color </PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-style">Apply Style</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="apply-custom-style">Apply Custom Style</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="change-font">Change Font</PrimaryButton>
            </div>
          </div>
          <h2>待用按钮</h2>
          <div className="button-wrap">
            <div className="padding">
              <PrimaryButton className="ms-Button" id="insert-text-into-range">Insert Abbreviation</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="insert-text-outside-range">Add Version Info</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="replace-text">Change Quantity Term</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="create-content-control">Create Content Control</PrimaryButton>
            </div>
            <div className="padding">
              <PrimaryButton className="ms-Button" id="replace-content-in-control">Rename Service</PrimaryButton>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
